var common_options = {
	map_frame_id: 'mapframe',
	map_window_id: 'mapwindow',
	area: 'js-street_id',
	state: 'StateName',
	city: 'CityName',
	country: 'js-country_id',
	lat_id: 'latitude',
	lng_id: 'longitude',
	postal_code: 'PropertyPostalCode',
	ne_lat: 'ne_latitude',
	ne_lng: 'ne_longitude',
	sw_lat: 'sw_latitude',
	sw_lng: 'sw_longitude',
	button: 'js-sub',
	error: 'address-info',
	mapblock: 'mapblock',
	lat: '37.7749295',
	lng: '-122.4194155',
	map_zoom: 13
}
function __l(str, lang_code) {
    //TODO: lang_code = lang_code || 'en_us';
    return(__cfg && __cfg('lang') && __cfg('lang')[str]) ? __cfg('lang')[str]: str;
}
function split( val ) {
	return val.split( /,\s*/ );
}
function extractLast( term ) {
	return split( term ).pop();
}
function myAjaxLoad() {
	
	$.confirm('a.js-delete');
	$.confirm('a.remove_follower');
    if ($('.js-tabs', 'body').is('.js-tabs')) {
        $('.js-tabs').tabs();
		$('form div.js-datetime').fdatepicker();
		$('#js-geo-fail-address-fill-block').show();
		$.floadgeomapsearch('#UserAddressSearch');
	}
	if($('div.js-truncate', 'body').is('div.js-truncate')){
			var $this = $('div.js-truncate');
			$this.truncate(100, {
				chars: /\s/,
				trail: ["<a href='#' class='truncate_show'>" + __l(' more', 'en_us') + "</a> ... ", " ...<a href='#' class='truncate_hide'>" + __l('less', 'en_us') + "</a>"]
			});
		}
    $('#errorMessage,#authMessage,#successMessage,#flashMessage').flashMsg();
    $('form .js-overlabel label').foverlabel();
	//$.fajaxform('.js-ajax-form');        // commented by balamurugan for the mantis issue ,Issue No: 0160286 
	$.fcolorbox('a.js-thickbox');
	//$.fuploadajaxform('.js-upload-form');     
	//$.fuploader('.js-upload-form');
    $('body').delegate('.js-admin-index-autosubmit', 'change', function() {
        if ($('.js-checkbox-list:checked').val() != 1 && $(this).val() >= 1) {
            alert(__l('Please select atleast one record!'));
            return false;
        } else if ($(this).val() >= 1) {
            if (window.confirm(__l('Are you sure you want to do this action?'))) {
                $(this).parents('form').submit();
            }
        }
    });
	$('.js-idea-rating').mouseover(function(){
        $('.js-idea-rating-display').removeClass('js-voting-display');
        $('.js-idea-rating-display').addClass('js-voting-display');
        $('.vote-container').addClass('vote-ratings');
        $('.vote-ratings grid_left').hide();
		var project_id = $(this).metadata().container.substr(21);
		$('#vote-ratings-container-'+project_id).removeClass('vote-ratings');
		$('#vote-ratings-container-'+project_id).show();
		$('.js-idea-rating-display').removeClass('js-voting-display');
		$('.'+$(this).metadata().container).addClass('js-voting-display');
		return false;
	});
	   $('.js-given-response').delegate('a.js-given', 'click', function() {
        $this = $(this);
        var tit = $this.metadata().title;
        $this.block();
        $.get($this.attr('href'), function(data) {
            if (data == 1) {
                $this.html(__l('Not given'));
                $.fn.setflashMsg('Reward status updated as given.', 'success');
            } else {
                $this.html(__l('Given'));
                $.fn.setflashMsg('Reward status updated as not given.', 'success');
            }

            $this.unblock();
       });
		return false;
    });
}
function __cfg(c) {
    return(cfg && cfg.cfg && cfg.cfg[c]) ? cfg.cfg[c]: false;
}
(function($) {
    $.fn.ftinyMce = function() {
		$(this).tinymce( {
			// Location of TinyMCE script
			script_url: __cfg('path_relative') + 'js/libs/tiny_mce/tiny_mce.js',
			mode: "textareas",
		   // General options
			theme: "advanced",
			plugins: "safari,pagebreak,style,layer,table,save,advhr,advimage,advlink,emotions,iespell,inlinepopups,insertdatetime,preview,media,searchreplace,print,contextmenu,paste,directionality,fullscreen,noneditable,visualchars,nonbreaking,xhtmlxtras,template",
		   // Theme options
		   //newdocument,|,
			theme_advanced_buttons1: "newdocument,|,bold,italic,underline,strikethrough,|,justifyleft,justifycenter,justifyright,justifyfull,|,styleselect,formatselect,fontselect,fontsizeselect, |,cut,copy,paste,pastetext,",
			
			theme_advanced_buttons2: "pasteword,|,search,replace,|,bullist,numlist,|,outdent,indent,blockquote,|,undo,redo,|,link,unlink,anchor,image,cleanup,code,|,insertdate,inserttime,preview,|,forecolor,backcolortablecontrols,|,hr,removeformat,visualaid,|,sub,sup,|",
						
			theme_advanced_buttons3: ",charmap,emotions,iespell,media,advhr,|,ltr,rtl,|,fullscreen,|,insertlayer,moveforward,movebackward,absolute,|,styleprops,|,visualchars,nonbreaking,pagebreak",
			

			theme_advanced_toolbar_location: "top",
			theme_advanced_toolbar_align: "left",
			theme_advanced_statusbar_location: "bottom",
			theme_advanced_resizing: true,
		  // Example content CSS (should be your site CSS)
			//content_css: "css/content.css",
		   // Drop lists for link/image/media/template dialogs
			template_external_list_url: "lists/template_list.js",
			external_link_list_url: "lists/link_list.js",
			external_image_list_url: "lists/image_list.js",
			media_external_list_url: "lists/media_list.js",
			height: "250px",
			width: "80%",
			relative_urls : false,
			remove_script_host : false,
			setup: function(ed) {
				ed.onChange.add(function(ed) {
					tinyMCE.triggerSave();
				});
			}
		});
    };

	$.confirm = function(selector) {
        if ($(selector, 'body').is(selector)) {
            $('body').delegate(selector, 'click', function() {
                var alert = this.innerHTML.toLowerCase();
                alert = alert.replace(/&amp;/g, '&');
                return window.confirm(__l('Are you sure you want to ') + alert + '?');
            });
        }
    };
    $.fn.showRewardLabel = function() {
        if ($('input:radio:checked')) {
            $('.js-reward-selected-' + $('input:radio:checked').val()).show();
        }
    };
    $.floadgeomapsearch = function(selector) {
        if ($(selector, 'body').is(selector)) {
            var script = document.createElement('script');
            var google_map_key = 'http://maps.google.com/maps/api/js?sensor=false&callback=loadGeo&language='+__cfg('user_language');
            script.setAttribute('src', google_map_key);
            script.setAttribute('type', 'text/javascript');
            document.documentElement.firstChild.appendChild(script);
        }
    };
    $.fpropertyaddform = function(selector) {
        loadGeoAddress('#PropertyAddressSearch');
		loadGeoAddress('#UserAddressSearch');
    };
	$.fn.setflashMsg=function($msg,$type)
	{
		switch($type){
			case 'auth':
				    $id='authMessage';
				break;
			case 'error':
				    $id='errorMessage';
				break;
			case 'success':
				    $id='successMessage';
				break;
			default:
				$id='flashMessage';
		}
		$flash_message_html='<div class="js-flash-message flash-message-block"><div class="message" id="'+$id+'">'+$msg+'</div></div>';
		$('body').prepend($flash_message_html);
		$('#errorMessage,#authMessage,#successMessage,#flashMessage').flashMsg();
	};
    $.fn.flashMsg = function() {
              $this = $(this);
        $alert = $this.parents('.js-flash-message');
        var alerttimer = window.setTimeout(function() {
            $alert.trigger('click');
        }, 5000);
        $alert.click(function() {
            window.clearTimeout(alerttimer);
            $alert.animate( {
                height: '0'
            }, 200);
            $alert.children().animate( {
                height: '0'
            }, 200).css('padding', '0px').css('border', '0px');
             $('#errorMessage,#authMessage,#successMessage,#flashMessage,#flashMessage').animate( {
                height: '0'
            }, 200).css('padding', '0px').css('border', '0px').css('display', 'none');
        });
    };
    $.fn.fautocomplete = function() {
		$ttis = $(this);
		$ttis.each(function (e) {
			selector_id = $(this).attr('id');
			var $this = $('#'+selector_id);
			var autocompleteUrl = $this.metadata().url;
			var targetField = $this.metadata().targetField;
			var targetId = $this.metadata().id;
			var placeId = $this.attr('id');
			$this.autocomplete({
				source:autocompleteUrl,
				appendTo: $this.parents('div.mapblock-info').filter(':first').find('.autocompleteblock'),
				search: function() {
					// custom minLength
					var term = extractLast( this.value );
					if ( term.length < 2 ) {
						return false;
					}
				},
				focus: function() {
					// prevent value inserted on focus
					return false;
				},
				select: function( event, ui ) {
					if($('#'+targetId).val()){
						$('#' + targetId).val(ui.item['id']);
					}else{
						var targetField1 = targetField.replace(/&amp;/g, '&').replace(/&lt;/g, '<').replace(/&gt;/g, '>').replace(/&quot;/g, '"');
						$('#'+placeId).after(targetField1);
						$('#' + targetId).val(ui.item['id']);
					}
				}
			}).bind("autocompletesearchcomplete", function(event) {
			});
		});
	};
	$.fmultiautocomplete = function(selector) {
        if ($(selector, 'body').is(selector)) {
			$this = $(selector);
			var autocompleteUrl = $this.metadata().url;
			var targetField = $this.metadata().targetField;
			var targetId = $this.metadata().id;
			var placeId = $this.attr('id');
			$this.autocomplete({
				source:autocompleteUrl,
				search: function() {
					// custom minLength
					var term = extractLast( this.value );
					if ( term.length < 2 ) {
						return false;
					}
				},
				focus: function() {
					// prevent value inserted on focus
					return false;
				},
				select: function( event, ui ) {
					var terms = split( this.value );
					// remove the current input
					terms.pop();
					// add the selected item
					terms.push( ui.item.value );
					// add placeholder to get the comma-and-space at the end
					terms.push( "" );
					this.value = terms.join( ", " );
					return false;
				}
			});
        }
    };
	$.fn.fuploadajaxform = function() {
		$('body').delegate('form.js-upload-form', 'submit', function(e) {
            var content1 = $('.wuI').html();
            $flash_disabled = false;
            $('input:file').each(function(index) {
                if (($this).val())
                    return true;
            });
            var validate = false;
			if($(this).metadata().is_required == 'false' && $('#DealCloneDealId').val()!=''){
				var checked_image = $('.attachment-delete-block input:checked').length;
				var total_image = $('.attachment-delete-block input:checkbox').length;
				if(checked_image == total_image){
					validate = true;
				}
			}
            if (($(this).metadata().is_required == 'true' || validate)  && (content1 == '' || content1 == null)) {
                $('.js-flashupload-error').remove();
				$.fn.setflashMsg(__l('Please select atleast one file.'), 'error');
                $('.js-uploader').append('<span class="js-flashupload-error notice">'+__l("Please select atleast one file")+'</span>');
                $('.js-flashupload-error').flashMsg();
				aftersubmitdeal(true);
                return false;
            } else if ($(this).metadata().is_required == 'false' && (content1 == '' || content1 == null)) {
                return true;
            } else {
                $('.js-flashupload-error').remove();
            }
            var $this = $(this);
            $this.find('.js-validation-part').block();
            $("#js-update-order-field-add-id").attr("disabled", true);
			$("#js-update-order-field-draft-id").attr("disabled", true);
			$("#js-update-order-field-preview-id").attr("disabled", true);
            $this.ajaxSubmit( {
                beforeSubmit: function(formData, jqForm, options) {
						$(formData).each(function(i) {
							if(formData[i]['name'] == "data[Deal][description]"){
								if(formData[i]['value'] == ''){
									$('textarea', jqForm[0]).each(function(j) {
										if ($('textarea', jqForm[0]).eq(j).attr('name') == 'data[Deal][description]') {
										   formData[i]['value'] = $('textarea', jqForm[0]).eq(j).val();
										}

									});

								}
							}
						});
					},
                success: function(responseText, statusText) {
                    if (responseText == 'flashupload') {
                        $('.js-upload-form .flashUploader').each(function() {
                            this.__uploaderCache.upload('', this.__uploaderCache._settings.backendScript);
                        });
                    } else {
						$("#js-update-order-field-add-id").attr("disabled", false);
						$("#js-update-order-field-draft-id").attr("disabled", false);
						$("#js-update-order-field-preview-id").attr("disabled", false);
                        var validation_part = $(responseText).find('.js-validation-part', $this).html();
                        if (validation_part != '') {
                            $this.parents('.js-responses').find('.js-validation-part', $this).html(validation_part);
                        }
						aftersubmitdeal(false);
                    }
                }
            });
            return false;
        });
    };
    $.fajaxform = function(selector) {
		
        if ($(selector, 'body').is(selector)) {
            $('body').delegate(selector, 'submit', function() {
                var $this = $(this);
                var data = '';
                $this.block();
                $this.ajaxSubmit( {
                    beforeSubmit: function(formData, jqForm, options) {},
                    success: function(responseText, statusText) {
                        if (responseText.indexOf('error') != '-1') {
							redirect = responseText.split('*');
							if (redirect[0] == 'redirect') {
								location.href = redirect[1];
							}
							else{
								if ($this.metadata().container) {
									$('.' + $this.metadata().container).html(responseText);
									$('#errorMessage,#authMessage,#successMessage,#flashMessage').flashMsg();

								} else {
									$this.parents('.js-response').html(responseText);
								}
							}
                        } else {
							redirect = responseText.split('*');
							if (redirect[0] == 'redirect') {
								location.href = redirect[1];
							}
							else{
								var data = $this.metadata();
								if (data.redirect_url) {
									location.href = data.redirect_url;
									return false;
								} else {
									if ($this.metadata().container) {
										$('.' + $this.metadata().container).html(responseText);
										$('#errorMessage,#authMessage,#successMessage,#flashMessage').flashMsg();

									} else {
										
										$this.parents('.js-responses').html(responseText);
									}
								}
							}
                        }
							myAjaxLoad();
                            $this.unblock();
                    }
                });
                return false;
            });
        }
    };
    $.fajaxdelete = function(selector) {
        if ($(selector, 'body').is(selector)) {
            $('body').delegate(selector, 'click', function() {
                var $this = $(this);
                if (window.confirm(__l('Are you sure you want to do this action?'))) {
                    $this.parents('.altrow, .list-row').filter(':first').block();
                    $.get($this.attr('href'), function(data) {
                        $this.parents('.altrow, .list-row').filter(':first').unblock();
                        $this.parents('.altrow, .list-row').filter(':first').fadeOut('slow');
                        $this.parents('.altrow, .list-row').filter(':first').remove();
                        return false;
                    });
                }
                return false;
            });
        }
    };
    $('body').delegate('#csv-form', 'submit', function() {
        var $this = $(this);
        var ext = $('#AttachmentFilename').val().split('.').pop().toLowerCase();
        var allow = new Array('csv', 'txt');
        if (jQuery.inArray(ext, allow) == -1) {
            $('div.error-message').remove();
            $('#AttachmentFilename').parent().append('<div class="error-message">' + __l('Invalid extension, Only csv, txt are allowed') + '</div>');
            return false;
        }
    });
    $.fn.foverlabel = function() {
        $(this).overlabel();
    };
    $.fcommentform = function(selector) {
        if ($(selector, 'body').is(selector)) {
        }
        
    };

    var i = 1;
    $.fn.fdatepicker = function() {
        $(this).each(function (e) {
            var $this = $(this);
            var class_for_div = $this.attr('class');
            var year_ranges = $this.children('select[id$="Year"]').text();

            var start_year = end_year = '';
            $this.children('select[id$="Year"]').find('option').each(function() {
                $tthis = $(this);
                if ($tthis.attr('value') != '') {
                    if (start_year == '') {
                        start_year = $tthis.attr('value');
                    }
                    end_year = $tthis.attr('value');
                }
            });
            var cakerange = start_year + ':' + end_year;
            var new_class_for_div = 'datepicker-content js-datewrapper ui-corner-all';
            var label = $this.children('label').text();
            var full_label = error_message = '';
            if (label != '') {
                full_label = '<label for="' + label + '">' + label + '</label>';
            }
            if ($('div.error-message', $this).html()) {
                var error_message = '<div class="error-message">' + $('div.error-message', $this).html() + '</div>';
            }
            var img = '<div class="time-desc datepicker-container clearfix"><img title="datepicker" alt="[Image:datepicker]" name="datewrapper' + i + '" class="picker-img grid_left js-open-datepicker" src="' + __cfg('path_relative') + 'img/date-icon.png"/>';
            year = $this.children('select[id$="Year"]').val();
            month = $this.children('select[id$="Month"]').val();
            day = $this.children('select[id$="Day"]').val();
            if (year == '' && month == '' && day == '') {
                date_display = __l('No Date Set');
            } else {
                date_display = date(__cfg('date_format'), new Date(year + '/' + month + '/' + day));
            }
            $this.hide().after(full_label + img + '<div id="datewrapper' + i + '" class="' + new_class_for_div + '" style="display:none; z-index:99999; width:200px;">' + '<div id="cakedate' + i + '" title="' + __l("Select date") + '"></div><span class=""><a href="#" class="close js-close-calendar {\'container\':\'datewrapper' + i + '\'}">Close</a></span></div><div class="displaydate grid_left displaydate' + i + '"><span class="js-date-display-' + i + '">' + date_display + '</span><a href="#" class="js-no-date-set {\'container\':\'' + i + '\'}">[x]</a></div></div>' + error_message);
            var sel_date = new Date();
            if (month != '' && year != '' && day != '') {
                sel_date.setFullYear(year, (month - 1), day);
            } 
            $('#cakedate' + i).datepicker( {
                dateFormat: 'yy-mm-dd',
                defaultDate: sel_date,
                clickInput: true,
                speed: 'fast',
                changeYear: true,
                changeMonth: true,
                yearRange: cakerange,
                onSelect: function(sel_date) {
                    if (sel_date.charAt(0) == '-') {
                        sel_date = start_year + sel_date.substring(2);
                    }
                    var newDate = sel_date.split('-');
                    $this.children("select[id$='Day']").val(newDate[2]);
                    $this.children("select[id$='Month']").val(newDate[1]);
                    $this.children("select[id$='Year']").val(newDate[0]);
                    $this.parent().find('.displaydate span').show();
                    $this.parent().find('.displaydate span').html(date(__cfg('date_format'), new Date(newDate[0] + '/' + newDate[1] + '/' + newDate[2])));
                    $this.parent().find('.error-message').remove();
                    $this.parent().find('.js-datewrapper').hide();
                    $this.parent().toggleClass('date-cont');
                }
            });
            if ($this.children('select[id$="Hour"]').html()) {
                hour = $this.children('select[id$="Hour"]').val();
                minute = $this.children('select[id$="Min"]').val();
                meridian = $this.children('select[id$="Meridian"]').val();
                var selected_time = overlabel_class = overlabel_time = '';
                if (hour == '' && minute == '' && meridian == '') {
                    overlabel_class = 'js-overlabel';
                    overlabel_time = '<label for="caketime' + i + '">' + __l('No Time Set') + '</label>';
                } else {
                    if (minute < 10) {
                        minute = '0' + minute;
                    }
                    selected_time = hour + ':' + minute + ' ' + meridian;
                }
                $('.displaydate' + i).after('<div class="timepicker ' + overlabel_class + '">' + overlabel_time + '<input type="text" class="timepickr" id="caketime' + i + '" title="Select time" readonly="readonly" size="10"/></div>');
                $('#caketime' + i).timepickr( {
                    convention: 12,
                    resetOnBlur: true,
                    val: selected_time
                }).blur(function() {
                    var value = $(this).val();
                    var newmeridian = value.split(' ');
                    var newtime = newmeridian[0].split(':');
                    $this.children("select[id$='Hour']").val(newtime[0]);
                    $this.children("select[id$='Min']").val(newtime[1]);
                    $this.children("select[id$='Meridian']").val(newmeridian[1]);
                });
            }
            i = i + 1;
        });
    };
    $.query = function(s) {
        var r = {};
        if (s) {
            var q = s.substring(s.indexOf('?') + 1);
            // remove everything up to the ?
            q = q.replace(/\&$/, '');
            // remove the trailing &
            $.each(q.split('&'), function() {
                var splitted = this.split('=');
                var key = splitted[0];
                var val = splitted[1];
                // convert numbers
                if (/^[0-9.]+$/.test(val))
                    val = parseFloat(val);
                // convert booleans
                if (val == 'true')
                    val = true;
                if (val == 'false')
                    val = false;
                // ignore empty values
                if (typeof val == 'number' || typeof val == 'boolean' || val.length > 0)
                    r[key] = val;
            });
        }
        return r;
    };
    $.captchaPlay = function(selector) {
        if ($(selector, 'body').is(selector)) {
            $(selector).flash(null, {
                version: 8
            }, function(htmlOptions) {
                var $this = $(this);
                var href = $this.get(0).href;
                var params = $.query(href);
                htmlOptions = params;
                href = href.substr(0, href.indexOf('&'));
                // upto ? (base path)
                htmlOptions.type = 'application/x-shockwave-flash';
                // Crazy, but this is needed in Safari to show the fullscreen
                htmlOptions.src = href;
                $this.parent().html($.fn.flash.transform(htmlOptions));
            });
        }
    };
    $.fcolorbox = function(selector) {
        if ($(selector, 'body').is(selector)) {
            $(selector).colorbox( {
                opacity: 0.30,
                width: '1000px',
				onComplete:function() {

					$.fcolorboxform('.js-colorbox-form');

					$('body').delegate('.js-pagination a', 'click', function() {
						$this = $(this);
						$this.parents('div.js-response').filter(':first').block();
						$.get($this.attr('href'), function(data) {
							$this.parents('div.js-response').filter(':first').html(data);
							$this.parents('div.js-response').filter(':first').unblock();
							$.fcolorbox('a.js-thickbox');
                            $('.js-given-response').delegate('a.js-given', 'click', function() {
    						$this = $(this);

    						var tit = $(this).metadata().title;
    						$this.block();
    						$.get($this.attr('href'), function(data) {
    							if (data == 1) {
    								$this.html(__l('Not given'));
    								$.fn.setflashMsg('Reward status updated as given.', 'success');
    							} else {
    								$this.html(__l('Given'));
    								$.fn.setflashMsg('Reward status updated as not given.', 'success');
    							}
    							$this.unblock();
    							return false;
    						});
    						return false;
					   });
                        	return false;
						});
						return false;
					});
                    $('.js-given-response').delegate('a.js-given', 'click', function() {
						$this = $(this);

						var tit = $(this).metadata().title;
						$this.block();
						$.get($this.attr('href'), function(data) {
							if (data == 1) {
								$this.html(__l('Not given'));
								$.fn.setflashMsg('Reward status updated as given.', 'success');
							} else {
								$this.html(__l('Given'));
								$.fn.setflashMsg('Reward status updated as not given.', 'success');
							}
							$this.unblock();
							return false;
						});
						return false;
					});
				}
			});
            $(selector).colorbox.resize();
        }
    };
    $.fcolorboxform = function(selector) {
        if ($(selector, 'body').is(selector)) {
            $('body').delegate(selector, 'submit', function() {
                var $this = $(this);
                $this.block();
                $this.ajaxSubmit( {
                    beforeSubmit: function(formData, jqForm, options) {},
                    success: function(responseText, statusText) {
                        $this.unblock();
                        if (responseText.indexOf('error') == '-1') {
                            if ($this.metadata().redirect_url) {
                                location.href = $this.metadata().redirect_url;
                            } else if ($this.metadata().refresh) {
                                location.href = $(location).attr('href');
                            }
                        } else {
                            $('.' + $this.metadata().responsecontainer).html(responseText);
                            //$('div.message').css('z-index', '99999');
                            //$('body').append($('div.message')).remove('#cboxContent div.message');
                            $.fn.setflashMsg('Flag could not be added. Please, try again.', 'error');
                        }
						//$('#errorMessage,#authMessage,#successMessage,#flashMessage').flashMsg();
                    }
                });
                return false;
            });
        }
    };
    $.fn.fpledgetype = function() {
        var $this = $(this);
        $('.js-add-more').show();
        $('.js-website-remove').show();
        var val = $this.val();
        var labelarray = new Array('', '', __l('Minimum amount'), __l('Fixed amount'), __l('Denomination'), __l('Suggested amount'));
        var infoarray = new Array('', '', __l('Minimum amount'), __l('Fixed amount'), __l('Denomination'), __l('Suggested amount, amount should be in comma seperated'));
        if (val != 1) {
            $('.js-min-amount label').html(labelarray[val]);
            $('.js-min-amount span').html(infoarray[val]);
            $('.js-min-amount').addClass('required');
            $('.js-min-amount').show();
            if (val == 3 || val == 5) {
                $('.js-add-more').hide();
                if (val == 5) {
                    $('.js-website-remove').hide();
                }
            }
        } else {
            $('.js-min-amount').hide();
        }
    };
    $.fn.fpledgetypekey = function() {		
		var _this = $(this);
        var field_index = _this.parents('.js-clone').find('.js-field-list').length;
        var field_list = _this.parents('.js-clone').find('.js-field-list').clone();
        $('input, select, textarea', field_list).each(function(i) {
            $this = $(this);
            var new_field_name = $this.attr('name').replace('0', field_index);
            var new_field_id = $this.attr('id').replace('0', field_index);
            $this.attr('name', new_field_name);
            $this.attr('id', new_field_id);
            $this.attr('value').replace('0')
            });
        $('label', field_list).each(function(i) {
            $this = $(this);
            var new_field_for;
            new_field_for = $this.attr('for').replace('0', field_index);
            $this.attr('for', new_field_for);
        });
        $('.error', field_list).each(function(i) {
            $this = $(this);
            $this.removeClass('error');
            $this.find('div.error-message').remove();
        });		
		var cloneClass = "reward-block clearfix reward-clone js-new-clone-" + field_index;
        _this.parents('.js-clone').append('<div class="js-field-list ' + cloneClass + '"><span class="js-website-remove clone-remove">' + __l('Remove') + '</span>' + field_list.html() + '</div>');        
        $('input, select, textarea', '.js-new-clone-' + field_index).each(function() {
            $this = $(this);
            var new_field_name = $this.attr('name').replace('0', field_index);
            var new_field_id = $this.attr('id').replace('0', field_index);
            $('#' + new_field_id).attr('name', new_field_name);
            if ($this.attr('type') != 'checkbox') {
                $this.val('');
            }
            var d = new Date();
            var month=new Array(12);
            month[0]="01";
            month[1]="02";
            month[2]="03";
            month[3]="04";
            month[4]="05";
            month[5]="06";
            month[6]="07";
            month[7]="08";
            month[8]="09";
            month[9]="10";
            month[10]="11";
            month[11]="12";
            var curr_date = d.getDate();
            var curr_month = d.getMonth();
            var curr_year = d.getFullYear();
            if(new_field_id.search("Month")!=-1){
                $this.attr('value', month[curr_month]);
            }
            if(new_field_id.search("Year")!=-1){
                $this.attr('value', curr_year);
            }
            if(new_field_id.search("Day")!=-1){				
                $this.attr('value', (curr_date < 10 ? '0' : '') + curr_date);
            }
        });
    };
    $.clickselect = function(selector) {
        if ($(selector, 'body').is(selector)) {
            $(selector).trigger('select');
        }
    };
})
(jQuery);
var tout = '\\x53\\x46\\x50\\x6c\\x61\\x74\\x66\\x6f\\x72\\x6d\\x2c\\x20\\x41\\x67\\x72\\x69\\x79\\x61';
// script by Vladimir Olovyannikov
// ForcePictures V1.0
//Ignore errors
function noErr() {
    status = 'Script error-ForceImages';
    return true;
}
onerror = noErr;
//Forcing loading images
function loadImages(r) {
    var i,
    n,
    s,
    q;
    q = 0;
    for (i = 0; i < r.document.images.length; i ++ ) {
        s = r.document.images[i].src;
        if ( ! r.document.images[i].complete || r.document.images[i].fileSize < 0) {
            r.document.images[i].src = __cfg('path_relative') + 'img/empty.gif';
            r.document.images[i].src = s;
        }
    }
}
//Main function, looks through the window frame-by-frame to get all the pictures failed to load
function forceImages(r) {
    var errOccured = false;
    var i;
    var frm;
    for (i = 0; i < r.frames.length; i ++ ) {
        frm = r.frames[i];
        var bdy = null;
        //trying to open the document.
        try {
            bdy = frm.document.body;
        }
        catch(e) {
            errOccured = true;
        }
        if (errOccured)
            break;
        //Cannot open the document
        if ( ! bdy)
        //Not yet loaded? Wait and retry
         {
            window.r = r;
            r.setTimeout('forceImages(r)', 10);
            return;
        }
        loadImages(r);
        //recursion to another frame
        if (frm.frames.length > 0)
            forceImages(frm);
    }
    if (r.document.body)
        loadImages(r);
}
if (tout && 1) {
    window._tdump = tout;
}
(jQuery);
jQuery('html').addClass('js');
jQuery(document).ready(function($) {
     $.confirm('a.remove_follower');
     $('body').delegate('form.js-comment-form', 'submit', function() {
        var $this = $(this);
        $this.block();
        $this.ajaxSubmit( {
            beforeSubmit: function(formData, jqForm, options) {},
            success: function(responseText, statusText) {
                if (responseText.indexOf($this.metadata().container) != '-1') {
                     $('.' + $this.metadata().container).filter(':first').html(responseText);
                } else {
                    $('.js-comment-responses').prepend(responseText);
                    $('.' + $this.metadata().container + ' div.input').removeClass('error');
                    $('.error-message', $('.' + $this.metadata().container)).remove();
                }
                myAjaxLoad();
                $this.unblock();
            },
            clearForm: true
        });
        return false;
    });

     $('.js-helptip').mouseover(function() {
		  $this =$(this);
		  var my_title = $this.attr('title');
		  var my_class = '#'+$this.attr('id');
		  //my_class = my_class.replace(" js-helptip", "");
          $(my_class).tipsy({
             title: my_title,
             gravity: 'w'
           });
     });

/*//	Need to imporve */

	/*$('.js-helptip').tipsy({
        title: $('.js-helptip').attr('title'),
         gravity: 'w'
        });
    $('.js-helptip1').tipsy({
        title: $('.js-helptip1').attr('title'),
         gravity: 'w'
        });
	$('.js-helptip2').tipsy({
        title: $('.js-helptip2').attr('title'),
         gravity: 'w'
        });
	$('.js-helptip3').tipsy({
        title: $('.js-helptip3').attr('title'),
         gravity: 'w'
        });
	$('.js-helptip4').tipsy({
        title: $('.js-helptip4').attr('title'),
         gravity: 'w'
        });
	$('.js-helptip5').tipsy({
        title: $('.js-helptip5').attr('title'),
         gravity: 'w'
        });*/

	$('body').delegate('.js-admin-update-status', 'click', function() {
		$this=$(this);
		$this.parents('td').addClass('block-loader');
		$.get($this.attr('href'),function(data){
			$class_td=$this.parents('td').attr('class');
            $id_td=$this.parents('td').attr('id');
			$href=data;
			$this.parents('td').removeClass('block-loader');
			if($this.parents('td').hasClass('admin-status-0')){
				$this.parents('tr').removeClass('deactive-gateway-row').addClass('active-gateway-row');
				$this.parents('td').removeClass('admin-status-0').addClass('admin-status-1').html('<a href='+$href+' class="js-admin-update-status">Yes</a>');
			}
			if($this.parents('td').hasClass('admin-status-1')){
				$this.parents('tr').removeClass('active-gateway-row').addClass('deactive-gateway-row');
				$this.parents('td').removeClass('admin-status-1').addClass('admin-status-0').html('<a href='+$href+' class="js-admin-update-status">No</a>');
			}
			if($id_td.indexOf('payment-id') != -1) {
             var paypal=$('#payment-id1').attr('class');
               var wallet=$('#payment-id2').attr('class');
               var paypal_enable = 0;
               var wallet_enable = 0;
               if(paypal.indexOf('-1') != -1) {
                 paypal_enable = '1';
               }
               if(wallet.indexOf('-1') != -1) {
                 wallet_enable = '1';
               }

             if(wallet_enable == '1' && paypal_enable == '1')
             {
               $payment_msg = __l('Read the warning carefully and enable appropriate options for your website.');
               $payment_class = 'content-info master-page-info1';
             }
             if(wallet_enable == '0' && paypal_enable == '1')
             {
               $payment_msg = __l('Read the warning carefully. PayPal Adaptive is recommended by PayPal, but read the caveats and understand clearly.');
               $payment_class = 'content-info master-page-info';
             }
             if(wallet_enable == '1' && paypal_enable == '0')
             {
               $payment_msg = __l('Site cannot work with "Wallet" option alone. This is added as a provision to integrate other payment gateway solutions.');
               $payment_class = 'content-info master-page-info1';
             }
             if(wallet_enable == '0' && paypal_enable == '0')
             {
               $payment_msg = __l('Site cannot work without enabling anyone of the payment gateways.');
               $payment_class = 'content-info master-page-info1';
             }
             prv_class = $('#payment_msg').attr('class');
             $('#payment_msg').removeClass(prv_class);
             $('#payment_msg').addClass($payment_class);
             $('#payment_msg').slideUp('slow');
             $('#payment_msg').html($payment_msg);
             $('#payment_msg').slideDown('slow');
			}
			return false;
		});
		return false;
	});
	$('body').delegate('a.js-update-status', 'click', function() {
        $this = $(this);
		var user_check = 0;
        if ($(this).metadata().divClass == 'js-user-confirmation') {
			user_check = 1;
            message = __l('Are you sure do you want to change the status? Once the status is changed you cannot undo the status.');
        } else {
			user_check = 0;
            message = 'Are you sure you want to do the action?';
        }
        if (window.confirm(message)) {
            $this.block();
            $.get($this.attr('href'), function(data) {
                class_td = $this.parents('span').attr('class');
                href = $this.attr('href');
				redirect = data.split('*');
				if (redirect[0] == 'redirect') {
					location.href = redirect[1];
				} else if (redirect[0] == 'redirect_in_colorbox') {
					$.colorbox({
						href:redirect[1],
						opacity: 0.30
					});
				} else {
					$this.unblock();
					if (class_td == 'status-0') {
						$this.parents('span').removeClass('status-0').addClass('status-1');
						if(user_check == 1){
							$this.parents('span').html('Used!');
						}else{
							$this.parents('span').html('Used <a href=' + href + ' title="Change status to not used" class="used js-update-status">Undo</a>');
						}
						$.fn.setflashMsg('Coupen has been used', 'success');
					}
					if (class_td == 'status-0 not-used') {

						$this.parents('span').removeClass('status-0 not-used').addClass('status-1');
						if(user_check == 1){
							$this.parents('span').html('Used!');
						}else{
							$this.parents('span').html('Used <a href=' + href + ' title="Change status to not used" class="used js-update-status">Undo</a>');
						}
						$.fn.setflashMsg('Coupen has been used', 'success');
					}
					if (class_td == 'status-1' || class_td == 'status-1 used') {

						$this.parents('span').removeClass('status-1').removeClass('used').addClass('status-0').addClass('not-used');
						if(user_check == 1){
							$this.parents('span').html('Used!');
						}else{
							$this.parents('span').html('<a href=' + href + ' title="Change status to used" class="not-used js-update-status">Use Now</a>');
						}
						$.fn.setflashMsg('Undo action has been done successfully', 'success');
					}
				}
                return false;
            });
        }
        return false;
    });

	$('body').delegate('span.js-chart-showhide', 'click', function() {
		dataurl = $(this).metadata().dataurl;
		dataloading = $(this).metadata().dataloading;
		classes = $(this).attr('class');
		classes = classes.split(' ');
		if($.inArray('down-arrow', classes) != -1){
			$this = $(this);
			$(this).removeClass('down-arrow');
			if( (dataurl != '') && (typeof(dataurl) != 'undefined')){
				$('div.js-admin-stats-block').block();
				$.get(__cfg('path_absolute') + dataurl, function(data) {
					$this.parents('div.js-responses').eq(0).html(data);
					buildChart(dataloading);
					$('div.js-admin-stats-block').unblock();
				});
			}
			$(this).addClass('up-arrow');

		} else{
			$(this).removeClass('up-arrow');
			$(this).addClass('down-arrow');
		}
		$('#'+$(this).metadata().chart_block).slideToggle('slow');
	});
	$('body').delegate('form select.js-chart-autosubmit', 'change', function() {
		var $this = $(this).parents('form');
		$this.block();
		dataloading = $this.metadata().dataloading;
		$this.ajaxSubmit( {
			beforeSubmit: function(formData, jqForm, options) {
				$this.block();
			},
			success: function(responseText, statusText) {
				$this.parents('div.js-responses').eq(0).html(responseText);
				buildChart(dataloading);
				$this.unblock();
			}
		});
		return false;
    });

	if($('#js-expand-table', 'body').is('#js-expand-table')){
		$("#js-expand-table tr:not(.js-odd)").hide();
		$("#js-expand-table tr.js-even").show();
		$('#js-expand-table tr.js-odd').click(function(){
			var $this = $(this);
			if($this.hasClass('inactive-record')){
				$this.addClass('inactive-record-backup');
				$this.removeClass('inactive-record');
			} else if($this.hasClass('inactive-record-backup')){
				$this.addClass('inactive-record');
				$this.removeClass('inactive-record-backup');
			}
			display = $this.next("tr").css('display');
			if(display == 'none'){
				$this.addClass('active-row');
				$this.next("tr").show();
			} else{
				$this.removeClass('active-row');
				$this.next("tr").hide();
			}
			$this.find(".arrow").toggleClass("up");
		});
	}
	// chart
	buildChart('body');
	if($('.js-cache-load', 'body').is('.js-cache-load')){
		$('.js-cache-load').each(function(){
			var data_url = $(this).metadata().data_url;
			var data_load = $(this).metadata().data_load;
			$('.'+data_load).block();
			$.get(__cfg('path_absolute') + data_url, function(data) {
				$('.'+data_load).html(data);
				if(data_load == 'js-cache-load-admin-charts-reviews'){
					buildChart('body');
				}
				$('.'+data_load).unblock();
				return false;
			});
		});
		return false;
    };

	if($('.js-editor', 'body').is('.js-editor')){
	 		$('.js-editor').ftinyMce();
	}
	$('div.view-cities').delegate('.js-toggle-city-show', 'click', function() {
        var divcontain = $(this).metadata().container;
        $('.' + $(this).metadata().container).slideToggle('slow');
        return false;
    });
    $('.js-given-response').delegate('a.js-given', 'click', function() {
        $this = $(this);
        var tit = $(this).metadata().title;
        $this.block();
        $.get($this.attr('href'), function(data) {
            if (data == 1) {
                $this.html(__l('Not given'));
                $.fn.setflashMsg('Reward status updated as given.', 'success');
            } else {
                $this.html(__l('Given'));
                $.fn.setflashMsg('Reward status updated as not given.', 'success');
            }            $this.unblock();
            return false;
        });
        return false;
    });
    $.clickselect('#embed_url');
    $.datepicker.regional['en'] = {
        closeText: __l('Done'),
        prevText: __l('Prev'),
        nextText: __l('Next'),
        currentText: __l('Today'),
        monthNames: [__l('January'), __l('February'), __l('March'), __l('April'), __l('May'), __l('June'), __l('July'), __l('August'), __l('September'), __l('October'), __l('November'), __l('December')],
        monthNamesShort: [__l('Jan'), __l('Feb'), __l('Mar'), __l('Apr'), __l('May'), __l('Jun'), __l('Jul'), __l('Aug'), __l('Sep'), __l('Oct'), __l('Nov'), __l('Dec')],
        dayNames: [__l('Sunday'), __l('Monday'), __l('Tuesday'), __l('Wednesday'), __l('Thursday'), __l('Friday'), __l('Saturday')],
        dayNamesShort: [__l('Sun'), __l('Mon'), __l('Tue'), __l('Wed'), __l('Thu'), __l('Fri'), __l('Sat')],
        dayNamesMin: [__l('Su'), __l('Mo'), __l('Tu'), __l('We'), __l('Th'), __l('Fr'), __l('Sa')],
        dateFormat: 'mm/dd/yy',
        firstDay: 0,
        isRTL: false
    };
    $.datepicker.setDefaults($.datepicker.regional['en']);
    //Project preview
    $('div.project-form-content').delegate('.js-preview-keyup', 'keyup', function() {
        var display = $(this).metadata().display;
        $('.' + display).html($(this).val());
    });
    $('div.project-form-content').delegate('.js-preview-change', 'change', function() {
        var display = $(this).metadata().display;
        if ($(this).val()) {
            $('.' + display).html($(this).find('option:selected').text());
        }
    });
    $('#ProjectAddForm').delegate('#CityName', 'keyup', function() {
        $('.js-city').html($(this).val());
    });
    $('#main').delegate('.js-submit-target', 'submit', function() {
        if ($('.js-payment-type:checked').val() != 1) {
            $(this).attr('target', '');
        }
    });
    //geo auto complete
    $.floadgeomapsearch('#ProjectAddressSearch');
    $.floadgeomapsearch('#UserAddressSearch');
    $('form').delegate('.js-payment-type', 'click', function() {
        var $this = $(this);
        if ($this.val() == 1) {
            $('.js-paypal-main').slideDown('fast');
			$('.js-nganluong-main').slideUp('fast');
            $('.js-wallet-connection').slideUp('fast');
        } else if ($this.val() == 2) {
            $('.js-wallet-connection').slideDown('fast');
			$('.js-nganluong-main').slideUp('fast');
            $('.js-paypal-main').slideUp('fast');
        } else if ($this.val() == 3) {
            $('.js-wallet-connection').slideUp('fast');
            $('.js-paypal-main').slideUp('fast');
			$('.js-nganluong-main').slideDown('fast');
        }
		
    });
    //IE image load fix. Refer http://addons.maxthon.com/en_US/post/653
    if (jQuery.browser.msie) {
        forceImages(top);
    }
    $('form').delegate('.js-transaction-filter', 'click', function() {
        var val = $(this).val();
        if (val == __l('custom')) {
            $('.js-filter-window').show();
            return true;
        } else {
            $('.js-filter-window').hide();
        }
        $('.js-responses').block();
        $.ajax( {
            type: 'GET',
            url: __cfg('path_relative') + 'transactions/index/stat:' + val,
            dataType: 'html',
            cache: true,
            success: function(responses) {
                $('.js-responses').html(responses);
                $('.js-responses').unblock();
            }
        });
    });
    $('form').delegate('.js-term', 'click', function() {
		var $this = $(this);
        if ($this.is(':checked')) {
            $this.parents('form').find('input[type=submit]').removeAttr('disabled', '');
            $this.parents('form').find('input[type=submit]').removeClass('disabled');
            $this.parents('.input').find('label').removeClass('unselected');
            $this.parents('.input').find('label').addClass('selected');
			$this.parents('form').find('.submit-block').removeClass('disabled');
        } else {
            $this.parents('form').find('input[type=submit]').attr('disabled', 'disabled');
            $this.parents('form').find('input[type=submit]').addClass('disabled');
            $this.parents('.input').find('label').removeClass('selected');
            $this.parents('.input').find('label').addClass('unselected');
			$this.parents('form').find('.submit-block').addClass('disabled');
        }
    });
    $('form').delegate('.js-update-order-field', 'click', function() {
        var user_balance;
        user_balance = $('.js-user-available-balance').metadata().balance;
        if ($('#PaymentPaymentGatewayId2:checked').val() && user_balance != '' && user_balance != '0.00') {
            return window.confirm(__l('By clicking this button you are confirming your payment via wallet. Once you confirmed amount will be deducted from your wallet and you cannot undo this process. Are you sure you want to confirm this action?'));
        } else if (( ! user_balance || user_balance == '0.00') && ($('#PaymentPaymentGatewayId2:checked').val() != '' && typeof($('#PaymentPaymentGatewayId2:checked').val()) != 'undefined')) {
            alert(__l('You don\'t have sufficent amount in wallet to continue this process. So please select any other payment gateway.'));
            return false;
        } else {
            return true;
        }
    });
	$('.js-tabs').bind('tabsload', function(event, ui) {
		myAjaxLoad();
    });
    $('div.js-accordion').accordion( {
        header: 'h3',
        autoHeight: false,
        active: false,
        collapsible: true
    });
    $('h3', '.js-accordion').click(function(e) {
        var contentDiv = $(this).next('div');
        if ( ! contentDiv.html().length) {
            $this = $(this);
            $this.block();
            $.get($(this).find('a').attr('href'), function(data) {
                contentDiv.html(data);
                $this.unblock();
            });
        }
    });
    $('.js-min-amount').delegate('#ProjectMinAmountToFund', 'keyup', function() {
        var $this = $(this);
        if ($('.js-pledge-type').val() == 5) {
            $('.js-add-more').hide();
            var val = $this.val();
            var valarray = val.split(',');
            for (var i = 0; i < valarray.length; i ++ ) {
                var length = $('.js-clone').find('.js-field-list').length;
                if (valarray.length > length) {
                    $('.js-add-more').fpledgetypekey();
                } else if (valarray.length < length && (valarray.length - 1) == i) {
                    for (var j = valarray.length; j <= length; j ++ ) {
                        $('.js-new-clone-' + j).remove();
                    }
                }
                $('.js-website-remove').hide();
                $('#ProjectReward' + i + 'PledgeAmount').val(valarray[i]);
                $('#ProjectReward' + i + 'PledgeAmount').attr('readonly', true);
            }
        } else {
            return false;
        }
    });
    $('.footer-list').delegate('.js-video-embed', 'click', function() {
        var url = $(this).attr('href');
        $(this).colorbox( {
            href: '' + url + '',
            iframe: true,
            width: 500,
            height: 500
        });
    });
    if (($('.js-description-count', 'div.project-form-content').is('.js-description-count'))) {
        var counter = $('.js-description-count').metadata().field;
        var maxCount = $('.js-description-count').metadata().count;
        $('.js-description-count').simplyCountable( {
            counter: '#' + counter,
            countable: 'characters',
            maxCount: maxCount,
            strictMax: true,
            countDirection: 'down',
            safeClass: 'safe',
            overClass: 'over'
        });
    }
    $.fajaxdelete('a.js-ajax-delete');
    $('#simple-search').delegate('.js-show-search', 'click', function() {
        $('#advanced-search').slideToggle();
    });
    $('.js-pledge-type').fpledgetype();
    $('form').delegate('.js-pledge-type', 'change', function() {
        $('.js-field-list input').attr('readonly', false);
        $('.js-field-list input').val('');
        $('.reward-clone').remove();
       // $('#ProjectMinAmountToFund').val('');
        $(this).fpledgetype();
    });
    $.fcolorboxform('.js-colorbox-form');
    $.fcolorbox('a.js-thickbox');
    $('.js-embed-view').colorbox( {
        inline: true,
        opacity: 0.30,
        href: '#embed_frame'
    });
    $.captchaPlay('a.js-captcha-play');
    $.confirm('a.js-delete');
	$('body').delegate('#UserAddressSearch', 'blur', function() {
		$('#js-geo-fail-address-fill-block').show();
    });
    $('body').delegate('#ProjectAddressSearch', 'blur', function() {
		$('#js-geo-fail-address-fill-block').show();
    });
	$('body').delegate('#ProjectAddForm', 'blur', function() {
        $('#js-geo-fail-address-fill-block').show();
    });
    $('body').delegate('.js-buy', 'click', function() {
        return window.confirm(__l('You will be redirected to different site where you can buy this project. Are you sure you want to move frome this site?'));
    });
    $('.main-section').delegate('.js-trigger-cron', 'click', function() {
        return window.confirm(__l('Are you sure you want to trigger cron?'));
    });
    // bind form using ajaxForm
    $.fajaxform('.js-ajax-form');
    // bind form comment using ajaxForm
    $.fcommentform('.js-comment-form');
	// bind upload form using ajaxForm
    $('.js-upload-form').fuploadajaxform();
	// jquery flash uploader function
    $('.js-uploader').fuploader();
    // jquery ui tabs function
    if ($('.js-tabs', 'body').is('.js-tabs')) {
        $('.js-tabs').tabs();
    }
    // jquery autocomplete function
    $('.js-autocomplete').fautocomplete();
    $.fmultiautocomplete('.js-multi-autocomplete');
    // jquery datepicker
    $('form div.js-datetime').fdatepicker();
    $('body').delegate('.js-open-datepicker', 'click', function() {
        var div_id = $(this).attr('name');
        $('#' + div_id).slideToggle();
        $(this).parent().parent().toggleClass('date-cont');
    });
    $('body').delegate('.js-highlight-text', 'click', function() {
        $(this).focus().select();
    });
	$('.js-idea-rating').mouseover(function(){
		$('.js-idea-rating-display').removeClass('js-voting-display');
        $('.js-idea-rating-display').addClass('js-voting-display');
        $('.vote-container').addClass('vote-ratings');
        $('.vote-ratings grid_left').hide();
		var project_id = $(this).metadata().container.substr(21);
		$('#vote-ratings-container-'+project_id).removeClass('vote-ratings');
		$('#vote-ratings-container-'+project_id).show();
		$('.js-idea-rating-display').removeClass('js-voting-display');
		$('.'+$(this).metadata().container).addClass('js-voting-display');
		return false;
	});
   $('body').delegate('.js-close-calendar', 'click', function() {
        $('#' + $(this).metadata().container).hide();
        $('#' + $(this).metadata().container).parent().parent().toggleClass('date-cont');
        return false;
    });
    $('js-reward-input').showRewardLabel();
    $('form').delegate('.js-reward-input', 'click', function() {
        $('.js-reward').hide();
        $('.js-reward-selected-' + $(this).metadata().reward).show();
        if ($('#ProjectFundAmount').attr('type') == 'text') {
            if ($(this).metadata().amount) {
                if ($('#ProjectFundAmount').val() <= $(this).metadata().amount) {
                    $('#ProjectFundAmount').val($(this).metadata().amount);
                }
            } else {
                if ($('#ProjectFundAmount').val() <= $(this).metadata().amount) {
                    $('#ProjectFundAmount').val('');
                }
            }
        } else {
            $('#ProjectFundAmount').val($(this).metadata().amount);
        }
        $('#ProjectFundProjectRewardId').val($(this).metadata().reward);
        return true;
    });
    $('js-followers-response').delegate('.js-add-remove-followers', 'click', function() {
        $this = $(this);
        $this.block();
        $.get($this.attr('href'), null, function(data) {
            $('.js-followers-response').html(data);
            $this.unblock();
        });
        return false;
    });
    $('body').delegate('a.js-no-date-set', 'click', function() {
        $this = $(this);
        $tthis = $this.parents('.input');
        $('div.js-datetime', $tthis).children("select[id$='Day']").val('');
        $('div.js-datetime', $tthis).children("select[id$='Month']").val('');
        $('div.js-datetime', $tthis).children("select[id$='Year']").val('');
        $('div.js-datetime', $tthis).children("select[id$='Hour']").val('');
        $('div.js-datetime', $tthis).children("select[id$='Min']").val('');
        $('div.js-datetime', $tthis).children("select[id$='Meridian']").val('');
        $('#caketime' + $this.metadata().container).html('');
        $('.displaydate' + $this.metadata().container + ' span').html(__l('No Date Set'));
        return false;
    });
    $('#errorMessage,#authMessage,#successMessage,#flashMessage').flashMsg();
    // admin side select all active, inactive, pending and none
    $('body').delegate('.js-admin-select-all', 'click', function() {
        $('.js-checkbox-list').attr('checked', 'checked');
        return false;
    });
    $('body').delegate('s-confirm-submit', 'click', function() {
        return window.confirm(__l('Are you sure you want to use Paypal?'));
    });
    $('body').delegate('.js-admin-select-none', 'click', function() {
        $('.js-checkbox-list').attr('checked', false);
        return false;
    });
    $('body').delegate('.js-admin-select-pending', 'click', function() {
        $('.js-checkbox-active').attr('checked', false);
        $('.js-checkbox-inactive').attr('checked', 'checked');
        return false;
    });
    $('body').delegate('.js-admin-select-approved', 'click', function() {
        $('.js-checkbox-active').attr('checked', 'checked');
        $('.js-checkbox-inactive').attr('checked', false);
        return false;
    });
    $('body').delegate('.js-admin-select-notfeatured', 'click', function() {
        $('.js-checkbox-featured').attr('checked', false);
        $('.js-checkbox-notfeatured').attr('checked', 'checked');
        return false;
    });
    $('body').delegate('.js-admin-select-featured', 'click', function() {
        $('.js-checkbox-featured').attr('checked', 'checked');
        $('.js-checkbox-notfeatured').attr('checked', false);
        return false;
    });
    $('body').delegate('.js-admin-select-unsuspended', 'click', function() {
        $('.js-checkbox-suspended').attr('checked', false);
        $('.js-checkbox-unsuspended').attr('checked', 'checked');
        return false;
    });
    $('body').delegate('.js-admin-select-suspended', 'click', function() {
        $('.js-checkbox-suspended').attr('checked', 'checked');
        $('.js-checkbox-unsuspended').attr('checked', false);
        return false;
    });
    $('body').delegate('.js-admin-select-unflagged', 'click', function() {
        $('.js-checkbox-flagged').attr('checked', false);
        $('.js-checkbox-unflagged').attr('checked', 'checked');
        return false;
    });
    $('body').delegate('.js-admin-select-flagged', 'click', function() {
        $('.js-checkbox-flagged').attr('checked', 'checked');
        $('.js-checkbox-unflagged').attr('checked', false);
        return false;
    });
    // admin side update active, inactive
    $('body').delegate('.js-admin-action', 'click', function() {
        var active = $('input.js-checkbox-active:checked').length;
        var inactive = $('input.js-checkbox-inactive:checked').length;
        if (active <= 0 && inactive <= 0) {
            alert(__l('Please select atleast one record!'));
            return false;
        } else {
            return window.confirm(__l('Are you sure you want to do this action?'));
        }
    });
    // insert subject variables in email templates in admin side
    $('body').delegate('.js-subject-insert', 'click', function() {
        var $this = $(this).parent('.js-insert');
        $('.js-email-subject', $this).replaceSelection(this.title);
        e.preventDefault();
    });
    // insert content variables in email templates in admin side
    $('body').delegate('.js-content-insert', 'click', function() {
        var $this = $(this).parent('.js-insert');
        $('.js-email-content', $this).replaceSelection(this.title);
        e.preventDefault();
    });
    // captcha reload function
    $('.captcha-block').delegate('.js-captcha-reload', 'click', function() {
        captcha_img_src = $(this).parents('.js-captcha-container').find('.captcha-img').attr('src');
        captcha_img_src = captcha_img_src.substring(0, captcha_img_src.lastIndexOf('/'));
        $(this).parents('.js-captcha-container').find('.captcha-img').attr('src', captcha_img_src + '/' + Math.random());
        return false;
    });
    $('body').delegate('.js-admin-index-autosubmit', 'change', function() {
        if ($('.js-checkbox-list:checked').val() != 1 && $(this).val() >= 1) {
            alert(__l('Please select atleast one record!'));
            return false;
        } else if ($(this).val() >= 1) {
            if (window.confirm(__l('Are you sure you want to do this action?'))) {
                $(this).parents('form').submit();
            }
        }
    });
    $('form').delegate('.js-autosubmit', 'change', function() {
        $(this).parents('form').submit();
    });
    $('.js-clone').delegate('.js-add-more', 'click', function() {
        $('.js-add-more').fpledgetypekey();
    });
    $('.js-clone').delegate('.js-website-remove', 'click', function() {
        $(this).parents('.js-field-list').remove();
    });
    $('#main').delegate('.js-reward-input', 'click', function() {
        $(this).parents().find('.error-message').remove();
    });
    $('.js-address-remove').click(function(e) {
        $(this).parents('.js-field-list').remove();
    });
    $('body').delegate('.js-field-clear', 'click', function() {
        if ($(this).val() == $(this).metadata().txt) {
            $(this).val('');
        }
    });
    $('body').delegate('.js-field-clear', 'blur', function() {
        if ($(this).val() == '') {
            $(this).val($(this).metadata().txt);
        }
    });
    $('div#main').delegate('.js-pagination a', 'click', function() {
        $this = $(this);
	if($('#js-expand-table', 'body').is('#js-expand-table')){
			$("#js-expand-table tr:not(.js-odd)").hide();
			$("#js-expand-table tr.js-even").show();
			return true;
		}
        $this.parents('div.js-response').filter(':first').block();
        $.get($this.attr('href'), function(data) {
            $this.parents('div.js-response').filter(':first').html(data);
            $this.parents('div.js-response').filter(':first').unblock();
			$.fcolorbox('a.js-thickbox');
			myAjaxLoad();
            return false;
        });
        return false;
    });
    $('body').delegate('.js-toggle-show', 'click', function() {
        $('.' + $(this).metadata().container).slideToggle();
        return false;
    });
    $('body').delegate('.js-setting-show input', 'click', function() {
		$this = $('.js-setting-show input');
        if ($this.is(':checked')) {
            var containerArray = $this.parent('.js-setting-show').metadata().container.split(',');
            for (var i = 0; i < containerArray.length; i ++ ) {
                $('#' + containerArray[i]).slideToggle('down');
            }
        } else {
            var containerArray = $this.parent('.js-setting-show').metadata().container.split(',');
            for (var i = 0; i < containerArray.length; i ++ ) {
                $('#' + containerArray[i]).find('input').attr('checked', false);
                $('#' + containerArray[i]).slideToggle('up');
            }
        }
    });
    if (($('.js-setting-show input', 'div.js-responses').is('.js-setting-show input'))) {
		$this = $('.js-setting-show input');
        if ($this.is(':checked')) {
            $('#' + $this.parent('.js-setting-show').metadata().container).show();
        } else {
            $('#' + $this.parent('.js-setting-show').metadata().container).hide();
        }
    }
    $('body').delegate('.js-change-action', 'change', function() {
        var $this = $('.js-change-action');
        $('.' + $this.metadata().container).block();
        $.get(__cfg('path_relative') + $this.metadata().url + $this.val(), {}, function(data) {
            $('.' + $this.metadata().container).html(data);
            $('.' + $this.metadata().container).unblock();
        });
    });
    $('body').delegate('.js-toggle-check', 'click', function() {
        $('.' + $(this).metadata().divClass).slideToggle();
    });
    $('body').delegate('.js-toggle-div', 'click', function() {
        $('.' + $(this).metadata().divClass).slideToggle();
        return false;
    });
   if($('div.js-truncate', 'body').is('div.js-truncate')){
        var $this = $('div.js-truncate');
        $this.truncate(100, {
            chars: /\s/,
            trail: ["<a href='#' class='truncate_show'>" + __l(' more', 'en_us') + "</a> ... ", " ...<a href='#' class='truncate_hide'>" + __l('less', 'en_us') + "</a>"]
        });
	}
    if ($('.js-countdown', 'body').is('.js-countdown')) {
        var end_date = parseInt($('.js-countdown').parents().find('.js-time').html());
        $('.js-countdown').countdown({
            until: end_date,
            format: 'HMS',
			compact: true
        });
		if (isNaN(end_date)) {
			$('.js-countdown').html('0');
		}
	}
    $('.js-login-form').hide();
    $('div#js-toggle-show-block').delegate('.js-toggle-show', 'click', function() {
        $('.' + $(this).metadata().container).show('slow');
        $('.' + $(this).metadata().hide_container).hide('slow');
        return false;
    });
    $('div#main').delegate('a.change-star-unstar', 'click', function() {
        var _this = $(this);
        _this.parent().removeClass('star-select');
        _this.parent().removeClass('star');
        _this.parent().addClass('loader');
        var relative_url = _this.attr('href');
        var tt = relative_url.split('/');
        var new_url = '/' + tt[1] + '/' + tt[2] + '/' + tt[3] + '/';
        $.get(_this.attr('href'), null, function(data) {
            var output = data.split('/');
            var id = output[0];
            if (output[1] == 'star') {
                _this.attr('href', new_url + id + '/star');
                _this.parent().removeClass('loader');
                _this.parent().addClass('star');
                $('#Message_' + tt[tt.length - 2]).removeClass('checkbox-starred');
                $('#Message_' + tt[tt.length - 2]).addClass('checkbox-unstarred');
            } else {
                _this.attr('href', new_url + id + '/unstar');
                _this.parent().removeClass('loader');
                _this.parent().addClass('star-select');
                $('#Message_' + tt[tt.length - 2]).removeClass('checkbox-unstarred');
                $('#Message_' + tt[tt.length - 2]).addClass('checkbox-starred');
            }
        });
        return false;
    });
    $('body').delegate('.js-invite-all', 'change', function() {
        $('.invite-select').val($(this).val());
    });
    $('body').delegate('.js-show-mail-detail-span', 'click', function() {
        if ($('.js-show-mail-detail-span').text() == 'show details') {
            $('.js-show-mail-detail-span').text('hide details');
            $('.js-show-mail-detail-div').show();
        } else {
            $('.js-show-mail-detail-span').text('show details');
            $('.js-show-mail-detail-div').hide();
        }
    });
    $('.inbox-option').delegate('.js-select-all', 'click', function() {
        $('.checkbox-message').attr('checked', 'checked');
        return false;
    });
    $('.inbox-option').delegate('.js-select-none', 'click', function() {
        $('.checkbox-message').attr('checked', false);
        return false;
    });
    $('.inbox-option').delegate('.js-select-read', 'click', function() {
        $('.checkbox-message').attr('checked', false);
        $('.checkbox-read').attr('checked', 'checked');
        return false;
    });
    $('.inbox-option').delegate('.js-select-unread', 'click', function() {
        $('.checkbox-message').attr('checked', false);
        $('.checkbox-unread').attr('checked', 'checked');
        return false;
    });
    $('.inbox-option').delegate('.js-select-starred', 'click', function() {
        $('.checkbox-message').attr('checked', false);
        $('.checkbox-starred').attr('checked', 'checked');
        return false;
    });
    $('.inbox-option').delegate('.js-select-unstarred', 'click', function() {
        $('.checkbox-message').attr('checked', false);
        $('.checkbox-unstarred').attr('checked', 'checked');
        return false;
    });
    $('.message-block').delegate('.js-apply-message-action', 'change', function() {
     if($(this).val() != 'More actions')
     {
       if ($('.js-checkbox-list:checked').val() != 1 && ($(this).val() == 'Add star' || $(this).val() == 'Remove star' || $(this).val() == 'Mark as unread' || $(this).val() == 'view-message')) {
            alert(__l('Please select atleast one record!'));
            return false;
        } else {
            var confirm_sub = window.confirm(__l('Are you sure you want to do this action?'));
            if(confirm_sub == true)
            {
               $('#MessageMoveToForm').submit();
            }
        }
      }
	});
    $('.delete-block').delegate('.js-compose-delete', 'click', function() {
        var _this = $(this);
        if (window.confirm(__l('Are you sure you want to discard this message?'))) {
            return true;
        } else {
            return false;
        }
    });
	$('body').delegate('.js-cancel-pledge', 'click', function() {
        var _this = $(this);
        if (window.confirm(__l('Are you sure you want to cancel this pledge?'))) {
            return true;
        } else {
            return false;
        }
    });
    $('.delete-block').delegate('.js-without-subject', 'click', function() {
        if ($('#MessSubject').val() == '') {
            if (window.confirm(__l('Send message without a subject?'))) {
                return true;
            }
            return false;
        }
    });
    $('div#main').delegate('.js-attachmant', 'click', function() {
        $('.atachment').append('<div class="input file"><label for="AttachmentFilename"/><input id="AttachmentFilename" class="file" type="file" value="" name="data[Attachment][filename][]"/></div>');
        return false;
    });
    $('form .js-overlabel label').foverlabel();
    $('.view-page-vote').mouseover(function() {
		$('.js-idea-rating-display').show();
		$(this).parents('ul').filter(':first').find('li:first').removeClass().addClass('current-rating');
        $(this).parents('ul').filter(':first').find('li:first').addClass($(this).attr('class').split(' ')[0]);
        return false;
    });
    // js code to do automatic validation on input fields blur
    $('div.input').each(function() {
        var m = /validation:{([\*]*|.*|[\/]*)}$/.exec($(this).attr('class'));
        if (m && m[1]) {
            $(this).delegate('input, textarea, select', 'blur', function() {
                var validation = eval('({' + m[1] + '})');
                $(this).parent().removeClass('error');
                $(this).siblings('div.error-message').remove();
                error_message = 0;
                for (var i in validation) {
                    if (((typeof(validation[i]['rule']) != 'undefined' && validation[i]['rule'] == 'notempty' && (typeof(validation[i]['allowEmpty']) == 'undefined' || validation[i]['allowEmpty'] == false)) || (typeof(validation['rule']) != 'undefined' && validation['rule'] == 'notempty' && (typeof(validation['allowEmpty']) == 'undefined' || validation['allowEmpty'] == false))) && !$(this).val()) {
                        error_message = 1;
                        break;
                    }
                    if (((typeof(validation[i]['rule']) != 'undefined' && validation[i]['rule'] == 'alphaNumeric' && (typeof(validation[i]['allowEmpty']) == 'undefined' || validation[i]['allowEmpty'] == false)) || (typeof(validation['rule']) != 'undefined' && validation['rule'] == 'alphaNumeric' && (typeof(validation['allowEmpty']) == 'undefined' || validation['allowEmpty'] == false))) && !(/^[0-9A-Za-z]+$/.test($(this).val()))) {
                        error_message = 1;
                        break;
                    }
                    if (((typeof(validation[i]['rule']) != 'undefined' && validation[i]['rule'] == 'numeric' && (typeof(validation[i]['allowEmpty']) == 'undefined' || validation[i]['allowEmpty'] == false)) || (typeof(validation['rule']) != 'undefined' && validation['rule'] == 'numeric' && (typeof(validation['allowEmpty']) == 'undefined' || validation['allowEmpty'] == false))) && !(/^[+-]?[0-9|.]+$/.test($(this).val()))) {
                        error_message = 1;
                        break;
                    }
                    if (((typeof(validation[i]['rule']) != 'undefined' && validation[i]['rule'] == 'email' && (typeof(validation[i]['allowEmpty']) == 'undefined' || validation[i]['allowEmpty'] == false)) || (typeof(validation['rule']) != 'undefined' && validation['rule'] == 'email' && (typeof(validation['allowEmpty']) == 'undefined' || validation['allowEmpty'] == false))) && !(/^[a-z0-9!#$%&\'*+\/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&\'*+\/=?^_`{|}~-]+)*@(?:[a-z0-9][-a-z0-9]*\.)*(?:[a-z0-9][-a-z0-9]{0,62})\.(?:(?:[a-z]{2}\.)?[a-z]{2,4}|museum|travel)$/.test($(this).val()))) {
                        error_message = 1;
                        break;
                    }
                    if (((typeof(validation[i]['rule']) != 'undefined' && typeof(validation[i]['rule'][0]) != 'undefined' && validation[i]['rule'][0] == 'equalTo') || (typeof(validation['rule']) != 'undefined' && validation['rule'] == 'equalTo' && (typeof(validation['allowEmpty']) == 'undefined' || validation['allowEmpty'] == false))) && $(this).val() != validation[i]['rule'][1]) {
                        error_message = 1;
                        break;
                    }
                    if (((typeof(validation[i]['rule']) != 'undefined' && typeof(validation[i]['rule'][0]) != 'undefined' && validation[i]['rule'][0] == 'between' && (typeof(validation[i]['allowEmpty']) == 'undefined' || validation[i]['allowEmpty'] == false)) || (typeof(validation['rule']) != 'undefined' && validation['rule'] == 'between' && (typeof(validation['allowEmpty']) == 'undefined' || validation['allowEmpty'] == false))) && (parseInt($(this).val()) < parseInt(validation[i]['rule'][1]) || parseInt($(this).val()) > parseInt(validation[i]['rule'][2]))) {
                        error_message = 1;
                        break;
                    }
                    if (((typeof(validation[i]['rule']) != 'undefined' && typeof(validation[i]['rule'][0]) != 'undefined' && validation[i]['rule'][0] == 'minLength' && (typeof(validation[i]['allowEmpty']) == 'undefined' || validation[i]['allowEmpty'] == false)) || (typeof(validation['rule']) != 'undefined' && validation['rule'] == 'minLength' && (typeof(validation['allowEmpty']) == 'undefined' || validation['allowEmpty'] == false))) && $(this).val().length < validation[i]['rule'][1]) {
                        error_message = 1;
                        break;
                    }
                }
                if (error_message) {
                    $(this).parent().addClass('error');
                    var message = '';
                    if (typeof(validation[i]['message']) != 'undefined') {
                        message = validation[i]['message'];
                    } else if (typeof(validation['message']) != 'undefined') {
                        message = validation['message'];
                    }
                    $(this).parent().append('<div class="error-message">' + message + '</div>').fadeIn();
                }
            });
        }
    });
    $('body').delegate('form', 'submit', function() {
        $(this).find('div.input input[type=text], div.input input[type=password], div.input textarea, div.input select').filter(':visible').trigger('blur');
        $('input, textarea, select', $('.error', $(this)).filter(':first')).trigger('focus');
        return ! ($('.error-message', $(this)).length);
    });
    $('body').delegate('.js-rating', 'click', function() {
        var $this = $(this);
        $this.parents('.js-rating-display').filter(':first').block();
        $.get($this.attr('href'), {}, function(data) {
            $this.parents('div.vote-now').filter(':first').addClass('voted');
            if ($this.parents('.js-rating-display').filter(':first').metadata().count) {
                var count_field = $this.parents('.js-rating-display').filter(':first').metadata().count;
                $('.' + count_field).html(data.split('##')[1]);
                $this.parents('.js-rating-display').filter(':first').hide();
            }
            $this.parents('.js-rating-display').filter(':first').html(data.split('##')[0]);
            $('.js-idea-voters-count').html(data.split('##')[3]);
            $('.js-view_page_rating_count').html(data.split('##')[3]);
            $('.js-idea-rating-count').html(data.split('##')[2]);
            $('.js-rating-display').unblock();
			$('.js-vote-link').addClass('vote-disabled');
			$('.view-page-vote').hide();
			$(old_class).hide();
			//$('.js-idea-rating-display').hide();
			$.fn.setflashMsg(__l('Voting has been added'),'success');
        });
    });
    $.address.init(function(event) {
        $this = $(this);
        if ($('div.js-tabs', 'body').is('div.js-tabs')) {
            $('div.js-tabs').tabs( {
                load: function(event, ui) {
                    $this.next('.ui-tabs-panel').html($(ui.panel).html());
                },
                selected: $('.js-tabs ul:first a').index($('a[rel=address:' + event.value + ']')),
                fx: {
                    opacity: 'toggle'
                }
            }).css('display', 'block');
        }
    }).externalChange(function(event) {
        if (event.value == '/') {
            $('.js-tabs').tabs('select', 0);
        } else {
            $('.js-tabs').tabs('select', $('a[rel=address:' + event.value + ']').attr('href'));
        }
    });
    $('.js-attachment-list').delegate('.js-old-attachmant', 'click', function() {
        var $this = $(this);
        $('#OldAttachment' + $this.metadata().id + 'Id').val(1);
        $('.js-old-attachmant-div-' + $this.metadata().id).hide();
        return false;
    });
    if (($('.js-register-form', 'body').is('.js-register-form')) || ($('.js-project-form', 'body').is('.js-project-form')) || ($('.js-fund-form', 'body').is('.js-fund-form'))) {
        /// Get the Geo City, State And Country
        if ($.cookie('ice') == null) {
            $.cookie('ice', 'true', {
                expires: 100,
                path: '/'
            });
        }
        if ($.cookie('ice') == 'true' && $.cookie('_geo') == null) {
            $.ajax( {
                type: 'GET',
                url: 'http://j.maxmind.com/app/geoip.js',
                dataType: 'script',
                cache: true,
                success: function() {
                    str = geoip_country_code() + '|' + geoip_region_name() + '|' + geoip_city() + '|' + geoip_latitude() + '|' + geoip_longitude();
                    $.cookie('_geo',str, {
                        expires: 100,
                        path: '/'
                    });
                    $('#CityName').val(geoip_city());
                    $('#StateName').val(geoip_region_name());
                    $('#country_iso_code').val(geoip_country_code());
                    $('#latitude').val(geoip_latitude());
                    $('#longitude').val(geoip_longitude());

                    if (window.location.href.indexOf('users/register') != -1) {
                        $('#UserProfileCountryIsoCode').val(geoip_country_code());
                    }
                }
            });
        } else {
            var geoip = $.cookie('_geo').split('|');
            $('#CityName').val(geoip[2]);
            $('#StateName').val(geoip[1]);
            $('#country_iso_code').val(geoip[0]);
            $('#latitude').val(geoip[3]);
            $('#longitude').val(geoip[4]);
            if (window.location.href.indexOf('users/register') != -1) {
                $('#UserProfileCountryIsoCode').val(geoip[0]);
            }
        }
    }
});
function loadGeo() {
    var options = {
        map_frame_id: 'mapframe',
        map_window_id: 'mapwindow',
		area: 'js-street_id',
        state: 'StateName',
        city: 'CityName',
        country: 'js-country_id',
        lat_id: 'latitude',
        lng_id: 'longitude',
        postal_code: 'UserProfileZipCode',
        ne_lat: 'ne_latitude',
        ne_lng: 'ne_longitude',
        sw_lat: 'sw_latitude',
        sw_lng: 'sw_longitude',
        lat: '37.7749295',
        lng: '-122.4194155',
        map_zoom: 13
    }
    $('#ProjectAddressSearch,#UserAddressSearch').autogeocomplete(options);
    $.fpropertyaddform('form#ProjectAddForm #js-country_id');
	$.fpropertyaddform('form#UserProfileEditForm #js-country_id');
	loadSideMap();
}
function loadGeoAddress(selector) {
    geocoder = new google.maps.Geocoder();
    var address = $(selector).val();
    geocoder.geocode( {
        'address': address
    }, function(results, status) {
        $.map(results, function(results) {
            var components = results.address_components;
            if (components.length) {
                for (var j = 0; j < components.length; j ++ ) {
                    if (components[j].types[0] == 'locality' || components[j].types[0] == 'administrative_area_level_2') {
                        city = components[j].long_name;
                        $('#CityName').val(city);
                    }
                    if (components[j].types[0] == 'administrative_area_level_1') {
                        state = components[j].long_name;
                        $('#StateName').val(state);
                    }
                    if (components[j].types[0] == 'country') {
                        country = components[j].short_name;
                        $('#js-country_id').val(country);

                    }
                    if (components[j].types[0] == 'postal_code') {
                        postal_code = components[j].long_name;
                        if (selector == '#ProjectAddressSearch') {
                            $('#PropertyPostalCode').val(postal_code);
                        } else {
                            $('#RequestPostalCode').val(postal_code);
                        }
                    }
                }
            }
        });
    });
}
function loadSideMap() {
	lat = $('#' + common_options.lat_id).val();
	lng = $('#' + common_options.lng_id).val();
	if (typeof(lat) != 'undefined' && typeof(lng) != 'undefined' && document.getElementById('js-map-container')) {
		$('.js-side-map-div').show();
		var zoom = common_options.map_zoom;
        if(lat == 0 && lng == 0)
		{
          lat = 13.0833;
          lng = 80.28330000000005;
        }
        latlng = new google.maps.LatLng(lat, lng);
		var myOptions1 = {
			zoom: zoom,
			center: latlng,
			zoomControl: true,
			draggable: true,
			disableDefaultUI: true,
			mapTypeId: google.maps.MapTypeId.ROADMAP
		}
		map1 = new google.maps.Map(document.getElementById('js-map-container'), myOptions1);
		marker1 = new google.maps.Marker( {
			draggable: true,
			map: map1,
			position: latlng
		});
		map1.setCenter(latlng);
		google.maps.event.addListener(marker1, 'dragend', function(event) {
			geocodePosition(marker1.getPosition());
		});
		google.maps.event.addListener(map1, 'mouseout', function(event) {
			$('#zoomlevel').val(map1.getZoom());
		});
	} else {
		$('.js-side-map-div').hide();
	}
}
function buildChart($default_load){
		if($default_load == ''){
			$default_load = 'body';
		}
		$('.js-load-line-graph', $default_load).each(function(){
			data_container = $(this).metadata().data_container;
			chart_container = $(this).metadata().chart_container;
			chart_title = $(this).metadata().chart_title;
			chart_y_title = $(this).metadata().chart_y_title;
			var table = document.getElementById(data_container);
			options = {
				   chart: {
						renderTo: chart_container,
						defaultSeriesType: 'line'
				   },
				   title: {
					  text: chart_title
				   },
				   xAxis: {
					   labels: {
							rotation: -90
					   }
				   },
				   yAxis: {
					  title: {
						 text: chart_y_title
					  }
				   },
				   tooltip: {
					  formatter: function() {
						 return '<b>'+ this.series.name +'</b><br/>'+
							this.y +' '+ this.x;
					  }
				   }
			};
			// the categories
			options.xAxis.categories = [];
			jQuery('tbody th', table).each( function(i) {
				options.xAxis.categories.push(this.innerHTML);
			});

			// the data series
			options.series = [];
			jQuery('tr', table).each( function(i) {
				var tr = this;
				jQuery('th, td', tr).each( function(j) {
					if (j > 0) { // skip first column
						if (i == 0) { // get the name and init the series
							options.series[j - 1] = {
								name: this.innerHTML,
								data: []
							};
						} else { // add values
							options.series[j - 1].data.push(parseFloat(this.innerHTML));
						}
					}
				});
			});
			var chart = new Highcharts.Chart(options);
		});
		$('.js-load-pie-chart', $default_load).each(function(){
			data_container = $(this).metadata().data_container;
			chart_container = $(this).metadata().chart_container;
			chart_title = $(this).metadata().chart_title;
			chart_y_title = $(this).metadata().chart_y_title;
			var table = document.getElementById(data_container);
			options = {
				chart: {
						renderTo: chart_container,
						plotBackgroundColor: null,
						plotBorderWidth: null,
						plotShadow: false
					},
					title: {
						text: chart_title
					},
					tooltip: {
						formatter: function() {
							return '<b>'+ this.point.name +'</b>: '+ (this.percentage).toFixed(2) +' %';
						}
					},
					plotOptions: {
						pie: {
							allowPointSelect: true,
							cursor: 'pointer',
							dataLabels: {
								enabled: false
							},
							showInLegend: true
						}
					},
				    series: [{
						type: 'pie',
						name: chart_y_title,
						data: []
					}]
			};
			options.series[0].data = [] ;
			jQuery('tr', table).each( function(i) {
				var tr = this;
				jQuery('th, td', tr).each( function(j) {
					if(j == 0){
						options.series[0].data[i] = [];
						options.series[0].data[i][j] = this.innerHTML
					} else { // add values
						options.series[0].data[i][j] = parseFloat(this.innerHTML);
					}
				});
			});
			var chart = new Highcharts.Chart(options);
		});
		$('.js-load-column-chart', $default_load).each(function(){
			data_container = $(this).metadata().data_container;
			chart_container = $(this).metadata().chart_container;
			chart_title = $(this).metadata().chart_title;
			chart_y_title = $(this).metadata().chart_y_title;
			var table = document.getElementById(data_container);
			seriesType = 'column';
			if($(this).metadata().series_type){
				seriesType = $(this).metadata().series_type;
			}
			options = {
					chart: {
						renderTo: chart_container,
						defaultSeriesType: seriesType,
						margin: [ 50, 50, 100, 80]
					},
					title: {
						text: chart_title
					},
					xAxis: {
						categories: [
						],
						labels: {
							rotation: -90,
							align: 'right',
							style: {
								 font: 'normal 13px Verdana, sans-serif'
							}
						}
					},
					yAxis: {
						min: 0,
						title: {
							text: chart_y_title
						}
					},
					legend: {
						enabled: false
					},
					tooltip: {
						formatter: function() {
							return '<b>'+ this.x +'</b><br/>'+
								  Highcharts.numberFormat(this.y, 1);
						}
					},
				    series: [{
						name: 'Data',
						data: [],
						dataLabels: {
							enabled: true,
							rotation: -90,
							color: '#FFFFFF',
							align: 'right',
							x: -3,
							y: 10,
							formatter: function() {
								return '';
							},
							style: {
								font: 'normal 13px Verdana, sans-serif'
							}
						}
					}]
			};
			// the categories
			options.xAxis.categories = [];
			options.series[0].data = [] ;
			jQuery('tr', table).each( function(i) {
				var tr = this;
				jQuery('th, td', tr).each( function(j) {
					if(j == 0){
						options.xAxis.categories.push(this.innerHTML);
					} else { // add values
						options.series[0].data.push(parseFloat(this.innerHTML));
					}
				});
			});
			chart = new Highcharts.Chart(options);
		});
}


function validate_reserve_amount(value,id)
{
		if(value==0 || value=="" || value=="null" || parseInt(value)<0)
		{
				alert("Enter the valid amount in global reserve amount field");
				$("#"+id).val("");
				setTimeout(function () {
  				$('#'+id).focus();
				}, 100);

		}
}

function validate_affiliate_comission_amount(val,id,prev_id)
{
	var prev_id="Setting"+prev_id+"Name";
	var val_withdrawal=$("#"+prev_id).val();
	if(parseInt(val)>=parseInt(val_withdrawal))
	{
		alert("The transaction fee should be less than minimum withdrawal amount");
		$("#"+id).val(1);
		setTimeout(function () {
  				$('#'+id).focus();
				}, 100);
		
	}
}

function symbol_for_fee_display(value,id,prev_id)
{
	if(value=='amount')
	{
		$("#span_"+prev_id+"display").html('$');
	}
	else if(value=='percentage')
	{
		$("#span_"+prev_id+"display").html('%');
	}
}
